package com.libl.controller;

import com.libl.pojo.DtsAdmin;
import com.libl.pojo.DtsBrand;
import com.libl.service.DtsAdminService;
import com.libl.service.DtsBrandService;
import com.libl.service.DtsCategoryService;
import com.libl.util.ResponseUtil;
import com.libl.vo.CatVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/brand")
public class DtsBrandController {

    @Autowired
    DtsBrandService brandService;
    //品牌制造商列表
    @GetMapping("/list")
    public Object list(@RequestParam(value="page",defaultValue="1",required= false) Integer page,
                       @RequestParam(value="limit",defaultValue="10",required= false) Integer limit,
                       String sort, String order,String name, Integer id){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin)subject.getPrincipal();

        List<Integer> brandId = null;
        //判断是否是品牌制造商
        if(subject.hasRole("品牌制造商")){
            brandId = brandService.findBrandIdsByAdminId(admin.getId());
        }
        //分页查询
        Map<String,Object> data = brandService.findByPage(page,limit,sort,order,name,id,brandId);
        //返回查询的数据
        return ResponseUtil.ok(data);
    }


    @Autowired
    DtsAdminService adminService;
    @Autowired
    DtsCategoryService categoryService;
    //分类和管理
    @GetMapping("/catAndAdmin")
    public Object catAndAdmin(){
        List<DtsAdmin> admins = adminService.findAll();

        ArrayList<Object> adminList = new ArrayList<>();
        //遍历
        for (DtsAdmin admin : admins) {
            HashMap<String,Object> map = new HashMap<>();
            map.put("value",admin.getId());
            map.put("label",admin.getUsername());
            //封装查询数据
            adminList.add(map);
        }

        List<CatVo> categoryList = categoryService.findCategoryList();

        HashMap<String, Object> data = new HashMap<>();
        data.put("adminList",adminList);
        data.put("categoryList",categoryList);
        //返回数据
        return ResponseUtil.ok(data);
    }

    //新增
    @PostMapping("/create")
    public Object create(@RequestBody DtsBrand brand){

        brandService.insert(brand);
        return ResponseUtil.ok(brand);
    }

    //删除
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsBrand brand){

        brandService.delete(brand);
        return ResponseUtil.ok();
    }

    //修改
    @PostMapping("/update")
    public Object update(@RequestBody DtsBrand brand){

        brandService.update(brand);
        return ResponseUtil.ok(brand);
    }

}
